package cn.est.utils;

import cn.est.config.OssConfig;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@Component
public class OssUtils {

    @Autowired
    private OssConfig ossConfig;

    public OSS getOssClient(){
        OSS ossClient=new OSSClientBuilder().build(ossConfig.getEndPoint(),ossConfig.getAccesskeyid(),ossConfig.getAccesskeysecret());
        return ossClient;
    }

    public String uploadByStream(File file,String fileName){
        String strResult="";
        OSS ossclient=null;
        try {
            InputStream is=new FileInputStream(file);
            ossclient=getOssClient();
            PutObjectResult putObjectResult=ossclient.putObject(ossConfig.getBucketName(),fileName,is);
            strResult=putObjectResult.getETag();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (Exception e){
           if (ossclient!=null){
               ossclient.shutdown();
           }
        }
        return strResult;
    }

    public void deleteFile(String bucketName,String fileName){
        OSS ossClient=getOssClient();
        ossClient.deleteObject(bucketName,fileName);
    }
}
